<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Order;
use App\Services\OrderService;
use Dingo\Api\Http\Request;

class OrderController extends BaseController
{

    public function index(Request $request)
    {
        $this->validate($request, [
           'type' => 'required|in:sell_out,buy_in'
        ]);
        $input = $request->input();
        $user_id = $this->getUserId();
        $order = new Order();
        if ($input['type'] == 'sell_out') {
            $list = $order->where('entity_type', Order::ENTITY_MATERIAL)->where('entity_user_id', $user_id);
        } else {
            $list = $order->where('entity_type', Order::ENTITY_MATERIAL)->where('user_id', $user_id);
        }
        $list = $list->where('status', Order::PAID_SUCCESS)
            ->withCertain('category', ['title'])
            ->withCertain('category', ['title'])
            ->withCertain('material', ['title', 'image_file', 'buy_type', 'amount','video_file'])->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }

    public function material_order_info(Request $request) {
        $this->validate($request, [
            'order_id' => 'required'
        ]);
        $input = $request->input();
        $order = Order::withCertain('user', ['nickname', 'avatar_url'])
            ->withCertain('merchant', ['nickname', 'avatar_url'])
            ->with('material')->withCertain('category', ['title'])->find($input['order_id']);
        if (!$order)
            return $this->failed('订单号不存在');
        if ($order->entity_user_id != $this->getUserId() && $order->user_id != $this->getUserId())
            return $this->failed('无权查看');

        return $this->success($order);
    }

    public function createPay(Request $request) {
        $this->validate($request, [
            'entity_id' => 'required',
            'entity_type' => 'required',
        ]);
        $input = $request->input();
        $user_id = $this->getUserId();
        $pay_platform = $request->input('pay_platform', 'miniapp');
        if (!in_array($pay_platform, ['miniapp', 'scan'])) {
            return $this->failed('pay_platform类型有误');
        }
        try {
            $response = OrderService::create_pay($user_id, $input['entity_id'], $input['entity_type'], $pay_platform);
            return $this->success($response);
        }catch (\Exception $e) {
            \Log::error($e->getMessage());
            return $this->failed($e->getMessage());
        }
    }
}

